package 剑指Offer._2130;

import java.util.Arrays;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/8/27 17:26
 * 顺时针打印矩阵
 * 算法：数组
 */
public class _29 {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(new _29().spiralOrder(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}})));
    }

    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return new int[0];
        int m = matrix.length, n = matrix[0].length;
        int[] ans = new int[m * n];
        int[][] dir = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        boolean[][] used = new boolean[m][n];
        int x = 0, y = 0;
        int flag = 0, cnt = 0;
        while (cnt < m * n) {
            ans[cnt++] = matrix[x][y];
            used[x][y] = true;
            int curx = x + dir[flag][0];
            int cury = y + dir[flag][1];
            if (curx < 0 || curx >= m || cury < 0 || cury >= n || used[curx][cury]) {
                flag = (flag + 1) % dir.length;
                x += dir[flag][0];
                y += dir[flag][1];
            } else {
                x = curx;
                y = cury;
            }
        }
        return ans;
    }

}
